package l1j.opqlo.Timer.Controler;

import java.util.Collection;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.Thread.PcOtherThreadPool;
import l1j.server.server.model.L1Party;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_Party;

/**
 * 隊伍更新時間軸(優化完成LOLI 2012-05-30)
 *
 * @author KZK
 *
 */
public class PartyTimer extends TimerTask {

	private static final Logger _log = Logger.getLogger(PartyTimer.class.getName());

	private ScheduledFuture<?> _timer;

	@Override
	public void run() {
		try {
			final Collection<L1PcInstance> all = L1World.getInstance().getAllPlayers();
			// 不包含元素
			if (all.isEmpty()) {
				return;
			}
			for (final L1PcInstance tgpc : all) {
				if (check(tgpc)) {
					tgpc.sendPackets(new S_Party(tgpc.getParty(), tgpc));
					Thread.sleep(50);
				}
			}
		} catch (final Exception e) {
			_log.log(Level.WARNING, "隊伍更新時間軸異常重啟", e);
			PcOtherThreadPool.get().cancel(this._timer, false);
			final PartyTimer partyTimer = new PartyTimer();
			partyTimer.start();
		}
	}

	public void start() {
		final int timeMillis = 5000;// 5秒
		this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this,timeMillis, timeMillis);
	}
	
	/**
	 * PC 執行 判斷
	 * @param tgpc
	 * @return true:執行 false:不執行
	 */
	private static boolean check(final L1PcInstance tgpc) {
		try {
			// 人物為空
			if (tgpc == null) {
				return false;
			}
			// 人物登出
			if (tgpc.getOnlineStatus() == 0) {
				return false;
			}
			// 中斷連線
			if (tgpc.getNetConnection() == null) {
				return false;
			}
			
			final L1Party party = tgpc.getParty();
			if (party == null) {
				return false;
			}
			/*if (!party.isLeader(tgpc)) {
				return false;
			}*/
			
		} catch (final Exception e) {
			_log.log(Level.SEVERE ,e.getLocalizedMessage(), e);
			return false;
		}
		return true;
	}
}
